import axios from 'axios'
import router from '../router/index'

function request(config, complete = true) {
  const instance = axios.create({
    baseURL: 'http://localhost:3000',
    method: 'GET',
    timeout: 9000
  })
  //携带cookie
  axios.defaults.withCredentials = true

  // 请求拦截
  instance.interceptors.request.use(request => {
    return request
  },
    // 请求发送失败 
    error => Promise.reject(error))

  //响应拦截
  instance.interceptors.response.use(response => {
    if (complete) {
      return response.data
    } else {
      return response
    }
  }, error => { //响应失败进入这个函数
    if(error.response?.status === 401){
    // if(error.response && error.response.status === 401) {
      router.push('/login')
    }
    return error
  })

  return instance(config)

}

export default request